package cube.net.socket;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Socket连接池
 * 
 * @author abiao
 */
public class SocketConnPool {

    /**
     * 连接池，保存客户端与服务端建立的长连接
     */
    private Map<String, SocketConnect> conns =
            new HashMap<String, SocketConnect>();

    /**
     * 添加Socket连接
     */
    public void add(SocketConnect conn) {
        conns.put(conn.toString(), conn);
    }

    /**
     * 移除连接
     */
    public void remove(String ip, int port) {
        remove(get(ip, port));
    }

    /**
     * 移除连接
     */
    public void remove(SocketConnect conn) {
        if (conn != null) {
            conn.close();
            conns.remove(conn.identify());
        }
    }

    /**
     * 获取连接
     */
    public SocketConnect get(String ip, int port) {
        return conns.get(ip + ":" + port);
    }

    /**
     * 根据标识(ip:port)获取连接
     */
    public SocketConnect get(String identify) {
        return conns.get(identify);
    }

    /**
     * 判断连接是否存在
     */
    public boolean exist(String ip, int port) {
        return conns.containsKey(ip + ":" + port);
    }

    /**
     * 返回所有连接
     */
    public List<SocketConnect> getAllConnects() {
        return new ArrayList<SocketConnect>(conns.values());
    }
}
